package com.hang.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;

import java.util.Date;

/**
 * @author youyou
 * <br/>date 2019-01-09
 */
@Slf4j
public class JwtUtil {

    private static final String STUDENT = "studentId";

    private static final String TEACHER = "teacherId";

    private static final String KEY = "123456";

    /**
     * 过期时间毫秒
     */

    private static long EXPIRATION_TIME = 24*60*60*1000;
    /**
     * 生成token
     *
     * @return
     * @author 刘朋
     * <br/>date 2019-01-09
     */
    public static String createStudentToken(String studentId) {
        Algorithm algorithm = Algorithm.HMAC256(KEY);

        Date expirationDate = new Date(System.currentTimeMillis()+EXPIRATION_TIME);
        //生成token
        return JWT.create().withClaim(STUDENT, studentId)
                .withExpiresAt(expirationDate)
                .sign(algorithm);
    }

    /**
     * 生成教师token
     *
     * @return
     * @author 刘朋
     * <br/>date 2019-01-09
     */
    public static String createTeacherToken(String teacherId) {
        Algorithm algorithm = Algorithm.HMAC256(KEY);

        Date expirationDate = new Date(System.currentTimeMillis()+EXPIRATION_TIME);

        //生成token
        return JWT.create().withClaim(TEACHER, teacherId)
                .withExpiresAt(expirationDate)
                .sign(algorithm);
    }

    /**
     * 获取教师ID
     *
     * @param token
     * @return
     * @author 刘朋
     * <br/>date 2019-03-08
     */
    public static String getTeacherId(String token) {
        return getValueByToken(token, TEACHER);
    }

    /**
     * 获取学生ID
     *
     * @param token
     * @return
     * @author 刘朋
     * <br/>date 2019-03-08
     */
    public static String getStudentId(String token) {
        return getValueByToken(token, STUDENT);
    }

    /**
     * 获取token中的值
     *
     * @param token
     * @param key
     * @return
     */
    public static String getValueByToken(String token, String key) {
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(KEY)).build();
        DecodedJWT decode = verifier.verify(token);
        return decode.getClaim(key).asString();
    }

    /**
     * 校验是否过期，过期返回true
     * @param token
     * @return
     * @author 刘朋
     * <br/>date 2019-03-12
     */
    public static boolean isExpires(String token){
        if(StringUtils.isBlank(token)){
            return true;
        }
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(KEY)).build();
        try {
            verifier.verify(token);
        }catch (JWTVerificationException e){
            return true;
        }
        return false;
    }

    /**
     * 验证token
     * @param token
     * @return
     */
    public static void verify(String token){
        try {
            JWT.require(Algorithm.HMAC256(KEY)).build().verify(token);  // 如果验证通过，则不会报错，否则会抛出异常
        }catch (NullPointerException npe){
            log.error("token无效");
        }
    }

    public static void main(String[] args) {
        try {
            String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdHVkZW50SWQiOiIxOTI1MTEwNDI0MCIsImV4cCI6MTY2NTE2MTg5Mn0.9EC1vri3fBb4rsUXt-K1LHQEb-xmtti__HEjX3iApvc";
            verify(token);
            System.out.println("token有效");
            System.out.println("id"+getStudentId(token));
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}